package h0722;

public class CircularLinkedList<T> {
    private Node<T> head = null;
    private Node<T> tail = null;
    private int size = 0;

    // 定义链表节点
    private static class Node<T> {
        T data;
        Node<T> next;

        Node(T data) {
            this.data = data;
        }
    }

    // 添加元素到链表末尾
    public void add(T data) {
        Node<T> newNode = new Node<>(data);
        if (head == null) {
            head = newNode;
            tail = newNode;
            tail.next = head;  // 循环指向
        } else {
            tail.next = newNode;
            tail = newNode;
            tail.next = head;  // 循环指向
        }
        size++;
    }

    // 打印链表中的所有元素
    public void printList() {
        if (head == null) {
            System.out.println("List is empty");
            return;
        }
        Node<T> current = head;
        do {
            System.out.print(current.data + " ");
            current = current.next;
        } while (current != head);
        System.out.println();
    }

    // 获取链表的大小
    public int getSize() {
        return size;
    }

    // 判断链表是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    // 从链表中移除一个元素
    public boolean remove(T data) {
        if (head == null) {
            return false;
        }

        Node<T> current = head;
        Node<T> previous = tail;

        do {
            if (current.data.equals(data)) {
                if (current == head) {
                    head = head.next;
                    tail.next = head;
                } else {
                    previous.next = current.next;
                    if (current == tail) {
                        tail = previous;
                    }
                }
                size--;
                return true;
            }
            previous = current;
            current = current.next;
        } while (current != head);

        return false;
    }

    public static void main(String[] args) {
        CircularLinkedList<Integer> list = new CircularLinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        System.out.println("Circular Linked List: ");
        list.printList();

        System.out.println("Size of the list: " + list.getSize());

        list.remove(3);
        System.out.println("After removing 3: ");
        list.printList();

        System.out.println("Size of the list: " + list.getSize());
    }
}
